package com.sg.service.biz.app.nb;

import cn.hutool.core.bean.BeanUtil;
import com.sg.common.util.CommonFunctionHelper;
import com.sg.dto.biz.app.common.DataFilterSpecRecBy;
import com.sg.dto.biz.app.req.*;
import com.sg.dto.biz.app.res.*;
import com.sg.dto.integration.component.QuerySemanticEngineDetailReqDto;
import com.sg.dto.integration.component.QuerySemanticEngineDetailRespDto;
import com.wicket.okrapp.common.baseinfo.BaseInfoDO;
import com.wicket.okrapp.common.baseinfo.BaseInfoHolder;
import com.wicket.okrcomponent.integration.TemplateEngineService;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;

/**
 * @author ： 手工接入方法
 * @version 1.0
 * @since 2022/5/28 15:32
 */
@Service
public class NbTimingTask {

    @Resource
    private TemplateEngineService fwCompTemplateEngineClient;

    /**
     * code:findLevelCode
     * name:M-查询找祖先列表（特殊方法）
     * desc:undefined
     * gen by moon at 8/28/2022, 4:07:02 PM
     **/
    @Trace(operationName = "M-查询找祖先列表（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public QueryLookAncestorNodeListRespDto queryLookAncestorNodeList(QueryLookAncestorNodeListReqDto reqDto) {
        QueryLookAncestorNodeListRespDto retData = new QueryLookAncestorNodeListRespDto();
        String oriCode = null;
        if (reqDto.getEvaObjTargetCycleCode() != null && !reqDto.getEvaObjTargetCycleCode().isEmpty()) {
            oriCode = reqDto.getEvaObjTargetCycleCode();
        }

        if (reqDto.getAssistNodeTypeObjectCode() != null && !reqDto.getAssistNodeTypeObjectCode().isEmpty()) {
            oriCode = reqDto.getAssistNodeTypeObjectCode();
        }

        if (reqDto.getComCode() != null && !reqDto.getComCode().isEmpty()) {
            oriCode = reqDto.getComCode();
        }

        if (oriCode == null || oriCode.isEmpty()) {
            return retData;
        }
        int dealSize = 4;
        while (oriCode.length() >= dealSize) {
            String oneCode = oriCode.substring(0, dealSize);
            if (oneCode != null && !oneCode.isEmpty()) {
                EvaObjTargetCycleDto elm = new EvaObjTargetCycleDto();
                elm.setEvaObjTargetCycleCode(oneCode);
                retData.getEvaObjTargetCycleList().add(elm);
                retData.getLookAncestorNodeList().add(oneCode);
            }
            dealSize = dealSize + 4;
        }
        retData.getLookAncestorNodeList().remove(oriCode);
        Collections.reverse(retData.getLookAncestorNodeList());
        return retData;
    }

    /**
     * code:publicFieldCache
     * name:M3更新公共字段缓存
     * desc:undefined
     * gen by moon at 8/28/2022, 4:07:45 PM
     **/
    @Trace(operationName = "M3更新公共字段缓存")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public RefreshPublicFieldCacheRespDto refreshPublicFieldCache(RefreshPublicFieldCacheReqDto reqDto) {
        if (BaseInfoHolder.contextHolder.get() != null) {
            BaseInfoHolder.contextHolder.remove();
        }
        BaseInfoDO domain = new BaseInfoDO();
        domain.setSpecSpaceId(reqDto.getSpaceId());
        domain.setSpecInductionRecordId(reqDto.getCreateInductionId());
        domain.setSpecAppId(reqDto.getAppId());
        CommonFunctionHelper.setBaseInfoToLocal(domain);
        return new RefreshPublicFieldCacheRespDto();
    }


    /**
     * code:publicFieldCache
     * name:M3执行业务应用公共字段推送内存（特殊方法）
     * desc:undefined
     * gen by moon at 9/22/2022, 12:01:59 AM
     **/
    @Trace(operationName = "M3执行业务应用公共字段推送内存（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizPublicFieldPushMemoryRespDto implementBizPublicFieldPushMemory(ImplementBizPublicFieldPushMemoryReqDto reqDto) {
        BaseInfoDO domain = new BaseInfoDO();
        if (BaseInfoHolder.contextHolder.get() != null) {
            BeanUtil.copyProperties(BaseInfoHolder.contextHolder.get().getBaseInfo(), domain);
            BaseInfoHolder.contextHolder.remove();
        }
        if (reqDto.getSpaceId() != null) {
            domain.setSpecSpaceId(reqDto.getSpaceId());
        }

        if (reqDto.getCreateInductionId() != null) {
            domain.setSpecInductionRecordId(reqDto.getCreateInductionId());
        }

        if (reqDto.getAppId() != null) {
            domain.setSpecAppId(reqDto.getAppId());
        }

        if (reqDto.getHighestOrgID() != null) {
            domain.setSpecHighestOrgID(reqDto.getHighestOrgID());
        }

        if (reqDto.getUserId() != null) {
            domain.setSpecUserId(reqDto.getUserId());
        }

        if (reqDto.getOriginalRoleMemberId() != null) {
            domain.setSpecOriginalRoleMemberId(reqDto.getOriginalRoleMemberId());
        }

        CommonFunctionHelper.setBaseInfoToLocal(domain);
        return new ImplementBizPublicFieldPushMemoryRespDto();
    }

    /**
     * code:receptionService
     * name:M3接收目标内容类型字段
     * desc:undefined
     * gen by moon at 9/28/2022, 6:07:20 AM
     **/
    @Trace(operationName = "M3接收目标内容类型字段")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementBizConstructAccessParameterFieldRespDto implementBizConstructAccessParameterField(ImplementBizConstructAccessParameterFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementBizConstructAccessParameterFieldRespDto.class);
    }

    /**
     * code:findAllLevelCodeList
     * name:3-3-09查OKR树找一级目标列表
     * desc:undefined
     * gen by moon at 10/5/2022, 12:23:39 PM
     **/
    @Trace(operationName = "3-3-09查OKR树找一级目标列表")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public AddMLevelUpContCodeRespDto addMLevelUpContCode(AddMLevelUpContCodeReqDto reqDto) {
        AddMLevelUpContCodeRespDto retData = new AddMLevelUpContCodeRespDto();
        if (reqDto.getEvaObjTypeCode() == null || reqDto.getEvaObjTypeCode().isEmpty()) {
            return retData;
        }
        int dealSize = 4;
        while (reqDto.getEvaObjTypeCode().length() >= dealSize) {
            String oneCode = reqDto.getEvaObjTypeCode().substring(0, dealSize);
            if (oneCode != null && !oneCode.isEmpty()) {
                retData.getEvaObjTargetCycleList().add(oneCode);
            }
            dealSize = dealSize + 4;
        }
        return retData;
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成“剩**小时就逾期”语义内容
     * desc:undefined
     * gen by moon at 10/5/2022, 4:20:21 PM
     **/
    @Trace(operationName = "M3-生成“剩**小时就逾期”语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CreateOverdueBurningTimeContentRespDto createOverdueBurningTimeContent(CreateOverdueBurningTimeContentReqDto reqDto) {
        //CREATE_OVERDUE_BURNING_TIME_CONTENT
        boolean bRetFlag = false;
        CreateOverdueBurningTimeContentRespDto retData = new CreateOverdueBurningTimeContentRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_OVERDUE_BURNING_TIME_CONTENT");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String timeDiffHours = "\\{timeDiffHours}";
            if (reqDto.getTimeDiffHours() != null && reqDto.getTimeDiffHours() != null) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, reqDto.getTimeDiffHours());
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成“宽限剩**小时就补报”语义内容
     * desc:undefined
     * gen by moon at 10/5/2022, 4:20:27 PM
     **/
    @Trace(operationName = "M3-生成“宽限剩**小时就补报”语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CreateGraceResidueTimeEndReportRespDto createGraceResidueTimeEndReport(CreateGraceResidueTimeEndReportReqDto reqDto) {
        boolean bRetFlag = false;
        CreateGraceResidueTimeEndReportRespDto retData = new CreateGraceResidueTimeEndReportRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_GRACE_RESIDUE_TIME_END_REPORT");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String timeDiffHours = "\\{timeDiffHours}";
            if (reqDto.getTimeDiffHours() != null && reqDto.getTimeDiffHours() != null) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, reqDto.getTimeDiffHours());
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成“补报剩**小时就结束汇报”语义内容
     * desc:undefined
     * gen by moon at 10/5/2022, 4:20:34 PM
     **/
    @Trace(operationName = "M3-生成“补报剩**小时就结束汇报”语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CreateReplenishResidueTimeEndReportRespDto createReplenishResidueTimeEndReport(CreateReplenishResidueTimeEndReportReqDto reqDto) {
        boolean bRetFlag = false;
        CreateReplenishResidueTimeEndReportRespDto retData = new CreateReplenishResidueTimeEndReportRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_REPLENISH_RESIDUE_TIME_END_REPORT");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String timeDiffHours = "\\{timeDiffHours}";
            if (reqDto.getTimeDiffHours() != null && reqDto.getTimeDiffHours() != null) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, reqDto.getTimeDiffHours());
            } else {
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, "---");
            }

            if (retConent != null && !retConent.isEmpty()) {
                retConent = retConent.replaceAll("---", "");
                retConent = retConent.replaceAll("（）", "");
                retData.setObjectName(retConent);
            }

            if (bRetFlag) {
                return retData;
            }

        }
        return retData;
    }

    /**
     * code:maxOrMinOfMultipleNum
     * name:M3计算数据集最大小值记录（特殊方法）
     * desc:undefined
     * gen by moon at 11/2/2022, 8:03:24 AM
     **/
    @Trace(operationName = "M3计算数据集最大小值记录（特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public CalculateDataBigMiniRecordRespDto calculateDataBigMiniRecord(CalculateDataBigMiniRecordReqDto reqDto) {
        CalculateDataBigMiniRecordRespDto retData = new CalculateDataBigMiniRecordRespDto();
        Long max = 0L;
        Long min = 9999999999L;
        String maxTaretPriId = "";
        String minTaretPriId = "";
        for (DataMiniRecordDto one : reqDto.getDataMiniRecordList()) {
            if (one.getOutputNum() >= max) {
                max = one.getOutputNum();
                maxTaretPriId = one.getContentID();
            }
            if (one.getOutputNum() <= min) {
                min = one.getOutputNum();
                minTaretPriId = one.getContentID();
            }
        }
        if (reqDto.getCalcMaxAndMin().equals("MAX")) {
            retData.setContentID(maxTaretPriId);
            retData.setOutputNum(max);
        } else {
            retData.setContentID(minTaretPriId);
            retData.setOutputNum(min);
        }

        return retData;
    }

    /**
     * code:dataFilterSpecRecBy
     * name:M3-执行数据集按入参过滤指定记录（所有分工指标列表排除当前指标）
     * desc:undefined
     * gen by moon at 11/30/2022, 5:03:24 PM
     **/
    @Trace(operationName = "M3-执行数据集按入参过滤指定记录（所有分工指标列表排除当前指标）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementDataFilterSpecRecByRespDto implementDataFilterSpecRecBy(ImplementDataFilterSpecRecByReqDto reqDto) {
        ImplementDataFilterSpecRecByRespDto retData = new ImplementDataFilterSpecRecByRespDto();
        for (DataFilterSpecRecBy one : reqDto.getDataFilterSpecRecByList()) {
            if (!one.getCommPrimaryKey().equals(reqDto.getCommPrimaryKey())) {
                retData.getDataFilterSpecRecByList().add(one);
            }
        }
        return retData;
    }

    /**
     * code:receptionService
     * name:约定出参：计算逾期参照时间
     * desc:undefined
     * gen by moon at 9/29/2023, 9:32:47 AM
     **/
    @Trace(operationName = "约定出参：计算逾期参照时间")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ObtainReceiveFieldRespDto obtainReceiveField(ObtainReceiveFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ObtainReceiveFieldRespDto.class);
    }

    /**
     * code:generateSemanticInstance
     * name:M3-生成“补报宽限剩**小时就结束”语义内容
     * desc:undefined
     * gen by moon at 10/1/2023, 2:33:22 PM
     **/
    @Trace(operationName = "M3-生成“补报宽限剩**小时就结束”语义内容")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public GenerateSemanticContentRespDto generateSemanticContent(GenerateSemanticContentReqDto reqDto) {
        //宽限剩{timeDiffHours}小时就结束汇报
        boolean bRetFlag = false;
        GenerateSemanticContentRespDto retData = new GenerateSemanticContentRespDto();
        String retConent = "";
        QuerySemanticEngineDetailReqDto querySemanticEngineDetailReqDto = new QuerySemanticEngineDetailReqDto();
        querySemanticEngineDetailReqDto.setTemplateSemanticEngineCode("CREATE_REPLENISH_RESIDUE_TIME_END_REPORT");
        QuerySemanticEngineDetailRespDto querySemanticEngineDetailRespDto = fwCompTemplateEngineClient.querySemanticEngineDetail(querySemanticEngineDetailReqDto).getData();
        if (querySemanticEngineDetailRespDto != null && querySemanticEngineDetailRespDto.getTemplateEngineTemplate() != null) {
            String timeDiffHours = "\\{timeDiffHours}";
            if (reqDto.getTimeDiffHours() != null && reqDto.getTimeDiffHours() != null) {
                bRetFlag = true;
                retConent = querySemanticEngineDetailRespDto.getTemplateEngineTemplate().replaceAll(timeDiffHours, reqDto.getTimeDiffHours());
            }
            retData.setObjectName(retConent);

        }
        return retData;
    }

    /**
     * code:receptionService
     * name:约定：汇报任务相关字段
     * desc:undefined
     * gen by moon at 1/2/2024, 8:24:58 AM
     **/
    @Trace(operationName = "约定：汇报任务相关字段")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementFourthReceivingFieldRespDto implementFourthReceivingField(ImplementFourthReceivingFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementFourthReceivingFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:约定出参：发送消息业务场景等
     * desc:undefined
     * gen by moon at 1/2/2024, 8:25:05 AM
     **/
    @Trace(operationName = "约定出参：发送消息业务场景等")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementAcceptFieldByStandardDataRespDto implementAcceptFieldByStandardData(ImplementAcceptFieldByStandardDataReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementAcceptFieldByStandardDataRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3-接收入参字段
     * desc:undefined
     * gen by moon at 5/3/2024, 11:31:08 PM
     **/
    @Trace(operationName = "M3-接收入参字段")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementElevenReceivingFieldRespDto implementElevenReceivingField(ImplementElevenReceivingFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementElevenReceivingFieldRespDto.class);
    }

    /**
     * code:receptionService
     * name:M3约定业务数据对象名等
     * desc:undefined
     * gen by moon at 5/30/2024, 11:05:51 PM
     **/
    @Trace(operationName = "M3约定业务数据对象名等")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementFiveReceivingFieldRespDto implementFiveReceivingField(ImplementFiveReceivingFieldReqDto reqDto) {
        return BeanUtil.toBean(reqDto, ImplementFiveReceivingFieldRespDto.class);
    }

    /**
     * code:endlessLoop
     * name:M3执行死循环(特殊方法）
     * desc:undefined
     * gen by moon at 5/30/2024, 11:05:52 PM
     **/
    @Trace(operationName = "M3执行死循环(特殊方法）")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementEndlessLoopRespDto implementEndlessLoop(ImplementEndlessLoopReqDto reqDto) {
        // TODO ruizhe skai dong ; 5/30/2024, 11:05:52 PM
        return new ImplementEndlessLoopRespDto();
    }

    /**
     * code:end
     * name:M3执行跳出循环（特殊方法)
     * desc:undefined
     * gen by moon at 5/30/2024, 11:05:54 PM
     **/
    @Trace(operationName = "M3执行跳出循环（特殊方法)")
    @Tags({@Tag(key = "参数", value = "arg[0]"),
            @Tag(key = "返回值", value = "returnedObj")})
    public ImplementEndLoopRespDto implementEndLoop(ImplementEndLoopReqDto reqDto) {
        // TODO ruizhe skai dong ; 5/30/2024, 11:05:54 PM
        return new ImplementEndLoopRespDto();
    }
    //手工接入方法
}
